package com.transaction.manage.util;

import java.lang.reflect.Method;

public class InvokeUtil {

    public static Object invokeMethodByName(final Class<?> clazz, final String methodName, final Object[] args) {
        Method method = getAccessibleMethodByName(clazz, methodName);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + clazz + "]");
        }
        try {
            return method.invoke(clazz.newInstance(), args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Method getAccessibleMethodByName (Class < ? > clazz, String methodName){
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }
}
